package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;


@Service
@Slf4j
public class UserServicempl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatProperties weChatProperties;

    //微信接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    public User login(UserLoginDTO userLoginDTO) {
        //调用微信接口服务,获取微信openid
        String openid = getOpenId(userLoginDTO.getCode());

        //判断openid是否有效
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断openid用户(微信用户)是否存在本地存在
        User user = userMapper.login(openid);

        if (user == null) {
            User build = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //添加到本地用户
            userMapper.insert(build);
            return build;
        } else

            return user;
    }

    private String getOpenId(String code) {
        HashMap map = new HashMap();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        //返回的是json格式数据,包括openid
        String respons = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(respons);
        String openid = (String) jsonObject.get("openid");
        return openid;
    }
}
